import * as React from 'react'
import { useRef, useState } from 'react'
import { Button, Input, Label } from 'v1-components'
import { CoreRepl, MiniPreviewRepl } from './Repls.js'

interface IResultPageProps {
  firstQuestion: string
}

function ResultPage(props: IResultPageProps) {
  const [questions, setQuestions] = useState<string[]>([props.firstQuestion])
  const [codes, setCodes] = useState<string[]>([''])
  const [selectedVersion, setSelectedVersion] = useState<number>(0)

  const additionalInputRef = useRef<HTMLInputElement>(null)

  const submit = () => {
    const input = additionalInputRef.current?.value?.trim() ?? ''
    if (input !== '') {
      setSelectedVersion(questions.length)
      setQuestions([...questions, input])
    }
  }

  const onEnter: React.DOMAttributes<HTMLInputElement>['onKeyPress'] = (e) => {
    if (e.code === 'Enter')
      submit()
  }

  const miniPreviews = codes.map((code, index) => (
    <div className="flex flex-col items-center mb-[20px] mx-[20px]" key={index.toString()}>
      <div
        className={`w-[240px] h-[180px] bg-white overflow-hidden rounded-2xl cursor-pointer border-solid border-4 hover:border-[#0070c1] ${index === selectedVersion ? 'border-[#a3a3a3]' : 'border-[#e3e3e3]'}`}
        onClick={() => setSelectedVersion(index)}
      >
        <MiniPreviewRepl code={code}></MiniPreviewRepl>
      </div>
      <span className="mt-2 bg-[#d3d3d3] w-[200px] rounded-2xl text-center text-[12px] px-4 text-nowrap overflow-hidden overflow-ellipsis h-6 leading-6 cursor-default select-none">{questions[index]}</span>
    </div>
  ))

  const coreRepls = questions.map((question, index) => (
    <CoreRepl
      hidden={index !== selectedVersion}
      key={index.toString()}
      onCodeChange={(c) => {
        const result = codes.slice(0)
        result[index] = c
        setCodes(result)
      }}
      question={question}
    />
  ))

  return (
    <main className="vx-dev-wrapper relative flex flex-col h-[100vh]">
      <div className="h-28 flex items-center justify-center">
        <h1 title={questions[selectedVersion]} className="text-2xl text-[#303030] w-[900px] border-2 border-[#f3f3f3] rounded-xl p-4 overflow-hidden text-nowrap flex items-center">
          <span className="text-4xl mr-2">🚀</span>
          {questions[selectedVersion]}
        </h1>
      </div>
      <div className="h-[80vh] flex-grow flex flex-row">
        <div className="h-full w-[280px] bg-[#f3f3f3] block overflow-auto border-y-[20px] border-[#f3f3f3] border-solid">
          {miniPreviews}
        </div>
        <div className="h-full w-[100vw] flex-1 border-y-[20px] border-r-[20px] border-[#f3f3f3]">
          {coreRepls}
        </div>
      </div>
      <div className="h-28 flex flex-col justify-center items-center">
        <div className="w-[900px] flex relative">
          <Input
            className="focus-visible:ring-0"
            id="website-description-input"
            placeholder="What do you want to modify? e.g. Make the title larger."
            ref={additionalInputRef}
            onKeyPress={onEnter}
          />
          <Button
            className="absolute right-0 text-2xl"
            onClick={() => submit()}
          >
            🚀
          </Button>
        </div>
      </div>
    </main>
  )
}

function SearchPage(props: { onSearch: (value: string) => void }) {
  const inputRef = useRef<HTMLInputElement>(null)

  const submit = () => {
    const input = inputRef.current?.value?.trim() ?? ''
    if (input !== '')
      props.onSearch(input)
  }

  const onEnter: React.DOMAttributes<HTMLInputElement>['onKeyPress'] = (e) => {
    if (e.code === 'Enter')
      submit()
  }

  return (
    <main className="p-0 m-0 w-full h-screen flex flex-col justify-center items-center">
      <div className="min-w-[900px] flex flex-col justify-center">
        <Label className="w-full text-center text-4xl font-semibold text-[#303030]" htmlFor="website-description-input">Describe the web page you want</Label>
        <div className="flex pt-6 relative">
          <Input
            className="focus-visible:ring-0"
            id="website-description-input"
            placeholder="e.g. Write a landing page for a website that sells shoes"
            ref={inputRef}
            onKeyPress={onEnter}
          />
          <Button
            className="absolute right-0 text-2xl"
            onClick={() => submit()}
          >
            🚀
          </Button>
        </div>
      </div>
    </main>
  )
}

export default function Home() {
  const [question, setQuestion] = useState<string>('')

  return question === '' ? <SearchPage onSearch={v => setQuestion(v)} /> : <ResultPage firstQuestion={question} />
}
